<?php

namespace Qy\Controller;

use Qy\Controller\QyBaseController;

/**
 * 学习中心-能力测评
 */
class AbilityCheckController extends QyBaseController {

    protected $arrPostIds = array();    //可查看的岗位ID
    protected $getPostId = 0;    //传递的岗位ID

    public function _initialize() {
        parent::_initialize();
        empty($this->iUserId) && $this->error("请登录!", -103);
        
        //岗位权限
        if (in_array($this->iRoleId, [1, 2])) {     //[1,2]表示拥有者、管理员
            $arrCateList = M("CategoryAll")->field('cate_id')->where(array('type' => 1))->select();
            foreach ($arrCateList as $val) {
                $arrPostIds[] = $val['cate_id'];
            }
            $this->arrPostIds = $arrPostIds;
        } else {
            $this->arrPostIds = [$this->iPostId];
        }
        empty($this->arrPostIds) && $this->error("您暂无岗位权限", -102);
    }

    //验证评测岗位权限
    private function _checkPostAuth() {
        //岗位是否匹配
        $this->getPostId = $getPostId = I('cate_id', 0, 'intval');
        if (empty($getPostId) || !in_array($getPostId, $this->arrPostIds)) {
            $this->error('该岗位无权限', -102);
        }

        //是否已测评
        $where['user_id'] = $this->iUserId;
        $where['cate_id'] = $getPostId;
        $checkInfo = M('UserCheck')->where($where)->select();
        if (!empty($checkInfo)) {
            $this->error("已经做过测评，不能重复提交");
        }
    }

    //试题列表：单选题和多选题，单选30题【初级18，中级12】，多选题10【初级6，中级4】，共40题
    public function questionList() {
        $this->_checkPostAuth();
        
        $arrPeriodIds = M()->table('qy_period as p')->field('p.period_id,s.sort')
                ->join('qy_curriculum as c ON c.curriculum_id = p.curriculum_id')
                ->join('qy_specialty as s ON s.specialty_id = c.specialty_id')
                ->where(array('p.status' => 1, 's.cate_id' => $this->getPostId, 's.sort' => array('in', [1, 2])))
                ->select();

        foreach ($arrPeriodIds as $val) {
            $period_ids[$val['sort']][] = $val['period_id'];
        }
        
        if(empty($period_ids)){
            $this->error('没有相关题目');
        }

        $Question = M('Question');
        $field = "question_id,title,question_img,addition,score";
        //初级-随机单选
        $simpleList1 = array();
        if(!empty($period_ids[1])){
            $simpleWhere['relat_id'] = array('in', $period_ids[1]);
            $simpleWhere['status'] = 1;
            $simpleWhere['type'] = 0;
            $simpleList1 = $Question->field($field)->where($simpleWhere)->order('rand()')->limit(18)->select();
        }
        
        $simpleList2 = array();
        if(!empty($period_ids[2])){
            //中级-随机单选
            $simpleWhere['relat_id'] = array('in', $period_ids[2]);
            $simpleWhere['status'] = 1;
            $simpleWhere['type'] = 0;
            $simpleList2 = $Question->field($field)->where($simpleWhere)->order('rand()')->limit(12)->select();
        }
        
        $multipleList1 = array();
        if(!empty($period_ids[1])){
            //初级-随机多选
            $multipleWhere['relat_id'] = array('in', $period_ids[1]);
            $multipleWhere['status'] = 1;
            $multipleWhere['type'] = 1;
            $multipleList1 = $Question->field($field)->where($multipleWhere)->order('rand()')->limit(6)->select();
        }
        
        $multipleList2 = array();
        if(!empty($period_ids[2])){
            //中级-随机多选
            $multipleWhere['relat_id'] = array('in', $period_ids[2]);
            $multipleWhere['status'] = 1;
            $simpleWhere['type'] = 1;
            $multipleList2 = $Question->field($field)->where($multipleWhere)->order('rand()')->limit(4)->select();
        }
        //合并+打乱
        $simpleList = array_merge($simpleList1, $simpleList2);
        shuffle($simpleList);
        $multipleList = array_merge($multipleList1, $multipleList2);
        shuffle($multipleList);

        $simple_total_score = 0;
        $multiple_total_score = 0;
        foreach ($simpleList as &$s_val) {
            $s_val['question_img'] = json_decode($s_val['question_img']);
            if(!empty($s_val['question_img'])){
                foreach($s_val['question_img'] as &$val){
                    $val = C('ADMIN_URL').$val;
                }
                unset($val);
            }
            $s_val['addition'] = json_decode($s_val['addition']);
            $simple_total_score += $s_val['score'];
        }
        foreach ($multipleList as &$m_val) {
            $m_val['question_img'] = json_decode($m_val['question_img']);
            if(!empty($m_val['question_img'])){
                foreach($m_val['question_img'] as &$val){
                    $val = C('ADMIN_URL').$val;
                }
                unset($val);
            }
            $m_val['addition'] = json_decode($m_val['addition']);
            $multiple_total_score += $m_val['score'];
        }
        $returnList['simple_count'] = count($simpleList);
        $returnList['simple_total_score'] = $simple_total_score;
        $returnList['multiple_count'] = count($multipleList);
        $returnList['multiple_total_score'] = $multiple_total_score;
        $returnList['total_score'] = $simple_total_score + $multiple_total_score;
        $returnList['simple_list'] = $simpleList;
        $returnList['multiple_list'] = $multipleList;

        $this->returnList($returnList);
    }

    //批量批改答案列表
    public function answerCheckList() {
        $this->_checkPostAuth();
        $jsonQuestionList = $_POST['question_list'];
        $arrQuestionList = json_decode($jsonQuestionList,true);
        foreach ($arrQuestionList as $val) {
            $question_ids[] = $val['question_id'];
        }
        if(empty($question_ids)){
            $this->error('参数错误');
        }
        $arrTrueAnswerList = M('Question')->field('question_id,answer,score')->where(array('question_id' => array('in', $question_ids)))->select();
        
        $total_score = 0;
        $check_total_score = 0;
        foreach ($arrTrueAnswerList as $val) {
            $total_score += $val['score'];
            foreach ($arrQuestionList as $vv) {
                if ($vv['question_id'] == $val['question_id']) {
                    $check_total_score += (!empty($vv['s_answer']) && $vv['s_answer'] == $val['answer']) ? intval($val['score']) : 0;
                }
            }
        }
        $cateName = M('CategoryAll')->where(array('cate_id' => $this->getPostId))->getField('cate_name');
        
        $Specialty = M("Specialty");
        $iUserId = $this->iUserId;
        $objOpenLock = new \Common\Model\OpenLockModel();
        
        if ($check_total_score >= $total_score * 0.4) {
            $recmd_cate = "中级";
            $data['specialty_sort'] = 2;    //中级解锁
            $specialtyList = $Specialty->field('specialty_id,sort')->where(array('cate_id'=>$this->getPostId,'status'=>1,'sort'=>array('in',[1,2])))->select();
            
            $arrSpecialtyIds = array();
            foreach($specialtyList as $val){
                $arrSpecialtyIds[$val['sort']] = $val['specialty_id'];
            }
            //开启初级和中级专业
            $objOpenLock->openOrCompleteSpecialty($iUserId, $arrSpecialtyIds[1], 1);
            $objOpenLock->openOrCompleteSpecialty($iUserId, $arrSpecialtyIds[2], 1);
        } else {
            $recmd_cate = "初级";
            $data['specialty_sort'] = 1;    //初级解锁
            $iSpecialtyId = $Specialty->where(array('cate_id'=>$this->getPostId,'status'=>1,'sort'=>1))->getField('specialty_id');
            //开启初级专业
            $objOpenLock->openOrCompleteSpecialty($iUserId,$iSpecialtyId,1);
            
        }
        $data['user_id'] = $this->iUserId;
        $data['cate_id'] = $this->getPostId;
        $data['check_score'] = $check_total_score;
        $data['create_time'] = date('Y-m-d H:i:s');
        $res = M("UserCheck")->add($data);
        if ($res) {
            $return['check_total_score'] = $check_total_score;
            $return['recmd_cate'] = $recmd_cate;
            $this->returnList($return);
        } else {
            $this->error('操作失败');
        }
    }

}
